package com.chonor.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.chonor.mall.bo.AdminUserDetails;
import com.chonor.mall.dao.AdminRoleRelationDao;
import com.chonor.mall.dto.AdminParam;
import com.chonor.mall.dto.UpdateAdminPasswordParam;
import com.chonor.mall.enums.GenderEnum;
import com.chonor.mall.enums.UserStatusEnum;
import com.chonor.mall.exception.Asserts;
import com.chonor.mall.mapper.*;
import com.chonor.mall.model.*;
import com.chonor.mall.service.AdminCacheService;
import com.chonor.mall.service.AdminService;
import com.chonor.mall.service.MenuService;
import com.chonor.mall.service.ResourceService;
import com.chonor.mall.util.EnumUtil;
import com.chonor.mall.util.JwtTokenUtil;
import com.chonor.mall.vo.AdminDetailVO;
import com.chonor.mall.vo.AdminVO;
import com.chonor.mall.vo.MenuVO;
import com.chonor.mall.vo.ResourceVO;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private AdminRoleRelationDao adminRoleRelationDao;

    @Autowired
    private AdminCacheService adminCacheService;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private ResourceMapper resourceMapper;



    @Override
    public Admin getAdminByUsername(String username) {
        Admin admin = adminCacheService.getAdmin(username);
        if(admin!=null) return  admin;
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<Admin> adminList = adminMapper.selectByExample(example);
        if (adminList != null && adminList.size() > 0) {
            admin = adminList.get(0);
            adminCacheService.setAdmin(admin);
            return admin;
        }
        return null;
    }

    @Override
    public Admin register(AdminParam adminParam) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminParam, admin);
        String code = RandomUtil.randomNumbers(6);
        admin.setCode("A"+code);
        admin.setCreateat(new Date());
        admin.setStatus(1);
        admin.setGender(Integer.valueOf(adminParam.getGender()));
        admin.setBirthday(DateUtil.parse(adminParam.getBirthday()));
        admin.setIsdelete(0);

        //查询是否有相同用户名的用户
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(admin.getUsername());
        List<Admin> umsAdminList = adminMapper.selectByExample(example);
        if (umsAdminList.size() > 0) {
            return null;
        }
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encodePassword);
        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                Asserts.fail("密码不正确");
            }
            if(!userDetails.isEnabled()){
                Asserts.fail("帐号已被禁用");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
//            updateLoginTimeByUsername(username);
//            insertLoginLog(username);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String oldToken) {
        return jwtTokenUtil.refreshHeadToken(oldToken);
    }

    @Override
    public Admin getItem(Long id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
    public AdminDetailVO getDetail(Long id) {
        if(Objects.isNull(id)) return null;
        AdminDetailVO adminDetailVO = new AdminDetailVO();

        //获取员工信息
        Admin admin = adminMapper.selectByPrimaryKey(id);
        adminDetailVO.setAdmin(convertAdmin(admin));

        //获取员工关联的角色
        List<Role> roles = getRoleList(id);
        adminDetailVO.setRoles(roles);

        List<Long> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
        //获取员工拥有的菜单
//        RoleMenuExample roleMenuExample = new RoleMenuExample();
//        roleMenuExample.createCriteria().andRoleIdIn(roleIds);
//        List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(roleMenuExample);
//        List<Long> menuIds = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
//        MenuExample menuExample = new MenuExample();
//        menuExample.createCriteria().andIdIn(menuIds);
//        List<Menu> menus = menuMapper.selectByExample(menuExample);
//        adminDetailVO.setMenus(menus);

        //获取员工拥有的资源
//        RoleResourceExample roleResourceExample = new RoleResourceExample();
//        roleResourceExample.createCriteria().andRoleIdIn(roleIds);
//        List<RoleResource> roleResources = roleResourceMapper.selectByExample(roleResourceExample);
//        List<Long> resourceIds = roleResources.stream().map(RoleResource::getResourceId).collect(Collectors.toList());
//        ResourceExample resourceExample = new ResourceExample();
//        resourceExample.createCriteria().andIdIn(resourceIds);
//        List<Resource> resources = resourceMapper.selectByExample(resourceExample);
//        adminDetailVO.setResources(resources);

        return adminDetailVO;
    }

    private AdminVO.Admin convertAdmin(Admin source){
        AdminVO.Admin target = new AdminVO.Admin();

        BeanUtils.copyProperties(source, target);
        target.setGender(EnumUtil.getMessage(GenderEnum.class, source.getGender()));
        target.setStatus(EnumUtil.getMessage(UserStatusEnum.class, source.getStatus()));
        target.setBirthday(DateUtil.formatDate(source.getBirthday()));
        target.setCreateAt(DateUtil.formatDate(source.getCreateat()));
        return target;
    }

    @Override
    public List<Admin> list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andUsernameLike("%" + keyword + "%");
            example.or(example.createCriteria().andNickNameLike("%" + keyword + "%"));
        }
        return adminMapper.selectByExample(example);
    }

    @Override
    public List<Admin> list(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andIsdeleteEqualTo(0);
        return adminMapper.selectByExample(adminExample);
    }

    @Override
    public Long count() {
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andIsdeleteEqualTo(0);
        long adminNum = adminMapper.countByExample(adminExample);
        return adminNum;
    }

    @Override
    public int update(Long id, Admin admin) {
        admin.setId(id);
        Admin rawAdmin = adminMapper.selectByPrimaryKey(id);
        if(rawAdmin.getPassword().equals(admin.getPassword())){
            //与原加密密码相同的不需要修改
            admin.setPassword(null);
        }else{
            //与原加密密码不同的需要加密修改
            if(StrUtil.isEmpty(admin.getPassword())){
                admin.setPassword(null);
            }else{
                admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            }
        }
        int count = adminMapper.updateByPrimaryKeySelective(admin);
        adminCacheService.delAdmin(id);
        return count;
    }

    @Override
    public int delete(Long id) {
        adminCacheService.delAdmin(id);
        Admin rawAdmin = adminMapper.selectByPrimaryKey(id);
        rawAdmin.setIsdelete(1);
        int count = adminMapper.updateByPrimaryKey(rawAdmin);
        adminCacheService.delResourceList(id);
        return count;
    }

    @Override
    public int updateRole(Long adminId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        AdminRoleExample adminRoleExample = new AdminRoleExample();
        adminRoleExample.createCriteria().andAdminIdEqualTo(adminId);
        adminRoleMapper.deleteByExample(adminRoleExample);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<AdminRole> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                AdminRole roleRelation = new AdminRole();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            adminRoleRelationDao.insertList(list);
        }
        adminCacheService.delResourceList(adminId);
        return count;
    }

    @Override
    public List<Role> getRoleList(Long adminId) {
        return adminRoleRelationDao.getRoleList(adminId);
    }

    @Override
    public List<Resource> getResourceList(Long adminId) {
        List<Resource> resourceList = adminCacheService.getResourceList(adminId);
        if(CollUtil.isNotEmpty(resourceList)){
            return  resourceList;
        }
        resourceList = adminRoleRelationDao.getResourceList(adminId);
        if(CollUtil.isNotEmpty(resourceList)){
            adminCacheService.setResourceList(adminId,resourceList);
        }
        return resourceList;
    }

    @Override
    public int updatePassword(UpdateAdminPasswordParam param) {
        if(StrUtil.isEmpty(param.getUsername())
                ||StrUtil.isEmpty(param.getOldPassword())
                ||StrUtil.isEmpty(param.getNewPassword())){
            return -1;
        }
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(param.getUsername());
        List<Admin> adminList = adminMapper.selectByExample(example);
        if(CollUtil.isEmpty(adminList)){
            return -2;
        }
        Admin umsAdmin = adminList.get(0);
        if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){
            return -3;
        }
        umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
        adminMapper.updateByPrimaryKey(umsAdmin);
        adminCacheService.delAdmin(umsAdmin.getId());
        return 1;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        //获取用户信息
        Admin admin = getAdminByUsername(username);
        if (admin != null) {
            List<Resource> resourceList = getResourceList(admin.getId());
            return new AdminUserDetails(admin,resourceList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
